package config

import (
	"fmt"
	"github.com/go-sql-driver/mysql"
	"net"
	"strings"
)

type DBConfig struct {
	DbConn     string `yaml:"DbConn"` //数据库类型,如mysql
	DbHost     string `yaml:"DbHost"`
	DbPort     string `yaml:"DbPort"`
	DbUser     string `yaml:"DbUser"`
	DbPassword string `yaml:"DbPassword"`
	DbName     string `yaml:"DbName"`

	MaxIdleConns int    `default:"0" yaml:"MaxIdleConns"`    //预留并发链接数
	MaxOpenConns int    `default:"0" yaml:"MaxOpenConns"`    //最大支持链接
	MaxLifetime  int    `default:"0" yaml:"ConnMaxLifetime"` //每个链接最大生存时间
	MaxIdleTime  int    `default:"0" yaml:"ConnMaxIdleTime"` //每个链接最大空闲时间
	MaxConcatLen string `default:"" yaml:"MaxConcatLen"`
}

func (c DBConfig) DSNForMysql(extends ...map[string]string) string {
	dbConfig := mysql.NewConfig()
	dbConfig.User = c.DbUser
	dbConfig.Passwd = c.DbPassword
	dbConfig.Net = "tcp"
	dbConfig.Addr = net.JoinHostPort(c.DbHost, c.DbPort)
	dbConfig.DBName = c.DbName
	dbConfig.MultiStatements = true
	dbConfig.RejectReadOnly = false
	extParam := make(map[string]string)
	if c.MaxConcatLen != "" {
		extParam["group_concat_max_len"] = c.MaxConcatLen
	}
	//扩展设置
	for _, m := range extends {
		for k, v := range m {
			extParam[k] = v
		}
	}
	dbConfig.Params = extParam
	return dbConfig.FormatDSN()

	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		c.DbUser, c.DbPassword, c.DbHost, c.DbPort, c.DbName)
}

func (c DBConfig) DSNForPgSql(extends ...map[string]string) string {

	extParam := map[string]string{}
	//扩展设置
	for _, m := range extends {
		for k, v := range m {
			extParam[k] = v
		}
	}

	params := []string{}
	for k, v := range extParam {
		params = append(params, fmt.Sprintf("%s=%s", k, v))
	}

	return fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s %s",
		c.DbHost, c.DbPort, c.DbUser, c.DbName, c.DbPassword, strings.Join(params, " "))
}
